package model.fshare.client;

import java.io.File;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;


import model.fshare.Interface.FileDownload;
import model.fshare.Interface.FileTransmistObserver;
import model.infocenter.ServerInformations;

public class FileDownloader implements FileDownload
{

	@Override
	public boolean download(int roomId, int userId, String fileName, FileTransmistObserver observer) 
	{
		File fileTOStore = new File( "FileRec/" + roomId + "/" + fileName );
		// If file has already exist,
		// just return.
		if ( fileTOStore.exists() )
		{
			return false;
		}
		
		try 
		{
			String serverIp = ServerInformations.getInstance().getIP();
			Socket socketForRequest = new Socket( serverIp, 5997 );
			PrintWriter requestSender = new PrintWriter( socketForRequest.getOutputStream() );
			requestSender.println( "" + roomId );
			requestSender.flush();
			requestSender.println( "" + userId );
			requestSender.flush();
			requestSender.println( fileName );
			requestSender.flush();
			
			// Before download, 
			// client must get permission from server.
			ObjectInputStream responseReader = new ObjectInputStream( socketForRequest.getInputStream() );
			boolean allowed = (Boolean) responseReader.readObject();
			if ( allowed )
			{
				FileDownloading fDownloading = new FileDownloading( fileTOStore, socketForRequest, observer );
				Thread dThread = new Thread( fDownloading );
				dThread.start();
				return true;
			}
		}
		catch ( Exception e ) 
		{
			// When exception happended,
			// delete the imcomplete local file.
			if ( fileTOStore.exists() )
			{
				fileTOStore.delete();
			}
			e.printStackTrace();
		}
		
		return false;
	}

}
